from rest_framework import serializers
from django.contrib.auth.models import Permission,Group
from django.contrib.contenttypes.models import ContentType
from users.models import User


class PermissionSerializer(serializers.ModelSerializer):
    # 指定 用户权限序列化器类
    class Meta:
        model = Permission
        fields = '__all__'


class ContentTypeSerializer(serializers.ModelSerializer):
    # 指定权限类型序列化器类
    class Meta:
        model = ContentType
        fields = ('id', 'name')


class GroupSerializer(serializers.ModelSerializer):
    # 指定用户组序列化器类
    class Meta:
        model = Group
        fields = '__all__'


class PermissionSimpleSerializer(serializers.ModelSerializer):
    # 指定 用户权限序列化器类
    class Meta:
        model = Permission
        fields = ('id','name')


class AdminSerializer(serializers.ModelSerializer):
    # 管理员管理序列化器类
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'mobile', 'user_permissions', 'groups', 'password')

        extra_kwargs = {
            'password': {
                'write_only': True,
                'required': False,
                'allow_blank': True
            }
        }

    def create(self, validated_data):
        # 重写 create
        validated_data['is_staff'] = True

        password = validated_data['password']

        if password is None:

            password = 123456789

            validated_data['password'] = password

        # 调用父类方法创建管理员用户
        user = super().create(validated_data)

        # 对密码进行加密处理
        user.set_password(password)
        user.save()

        return user

    def update(self, instance, validated_data):
        # 修改管理员用户湖信息
        password = validated_data.get('password')

        user = super().update(instance, validated_data)

        if password:
            user.set_password(password)
            user.save()
        return user


class GroupSimpleSerializer(serializers.ModelSerializer):
    # 用户组简单展示
    class Meta:
        model = Group
        fields = ('id', 'name')

